<template>
	<view class="search-content">
		<uni-search-bar class="uni-mt-10" radius="100" :focus="true" v-model="searchTitle" placeholder="搜大学/搜专业"
			cancelButton="none" @confirm="search" />
		<uni-section class="mb10" title="搜索历史" type="circle" titleFontSize="14" titleColor="#000">
			<template v-slot:right>
				<uni-icons type="trash" color="#a1a1a1" size="20" @click="dialogOpen"></uni-icons>
			</template>
		</uni-section>
		<view class="pb20" v-if="empty">
			<pinapp-empty-page></pinapp-empty-page>
		</view>
		<view v-else class="search-content-bottom">
			<text class="text" v-for="(searchData, index) in searchDataList"
				:key="'search'+index" @click="clickSearchHistory(searchData)">{{ searchData }}</text>
		</view>
	</view>
	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="warn" cancelText="取消" confirmText="确定" title="提示" content="您确定要清除搜索历史记录么？"
				@confirm="dialogConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchTitle: "",
				searchDataList: [],
				empty: false
			}
		},
		onShow() {
			this.getSearchData()
		},
		onLoad(option) {
			this.searchTitle = option.title
		},
		methods: {
			getSearchData() {
				this.searchDataList = uni.getStorageSync('search_history')
				this.empty = Boolean(this.searchDataList.length === 0)
			},
			search(res) {
				if (res.value) {
					this.addSearchToStorage(res.value)
					uni.navigateTo({
						url: '/pages/index/searchList?title=' + res.value
					})
				}
			},
			addSearchToStorage(searchTitle) {
				let searchHistory = uni.getStorageSync('search_history')
				let searchHistoryNew = []
				searchHistoryNew.push(searchTitle)
				if (searchHistory) {
					searchHistory.forEach((item, index) => {
						if (index < 9) {
							searchHistoryNew.push(item)
						}
					})
				}
				uni.setStorage({
					key: "search_history",
					data: searchHistoryNew
				})
			},
			dialogOpen() {
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {
				uni.removeStorageSync("search_history")
				uni.showToast({
					title: "清除成功",
					icon: 'success'
				});
				this.getSearchData()
			},
			clickSearchHistory(searchData){
				this.searchTitle = searchData
				uni.navigateTo({
					url: '/pages/index/searchList?title=' + searchData
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.search-content {
		background-color: #fff;
	}

	.search-content-bottom {
		padding: 15px;
		display: flex;
		flex-wrap: wrap;
		font-size: 14px;

		.text {
			background-color: #F8F8F8;
			margin: 0 10px 10px 0;
			padding: 8px;
		}
	}
	.pb20{
		padding-bottom: 20px;
	}
</style>
